﻿using System.Xml;
using VASJ.Common;

namespace VASJ.Model
{
    public class LocalizationManager
    {
        public static Localization LocalizationInstant;

        public static void Run()
        {
            #region Configuration

            LocalizationManager.LocalizationInstant = SerializationTool<Localization>.Load(Constants.PathCommonLocation);

            if (LocalizationManager.LocalizationInstant == null)
            {
                SerializationTool<Localization>.Save(Constants.PathCommonLocation, new Localization());

                LocalizationManager.SaveWithEndcoding();

                LocalizationManager.LocalizationInstant = SerializationTool<Localization>.Load(Constants.PathCommonLocation);
            }

            #endregion Configuration
        }

        public static void SaveWithEndcoding()
        {
            string filename = Constants.PathCommonLocation + Constants.LANGUAGE_FILE_NAME;

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(filename);

            XmlDeclaration xmlDecl = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

            if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
            {
                xmlDoc.ReplaceChild(xmlDecl, xmlDoc.FirstChild);
            }
            else
            {
                xmlDoc.InsertBefore(xmlDecl, xmlDoc.DocumentElement);
            }

            xmlDoc.Save(filename);
        }

        public static void Save()
        {
            if (LocalizationManager.LocalizationInstant != null)
            {
                SerializationTool<Localization>.Save(Constants.PathCommonLocation, LocalizationManager.LocalizationInstant);
                SaveWithEndcoding();
            }
        }
    }
}
